package lyq.spec.edu.week13_class02;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;

    private NetworkChangeReceiver networkChangeReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //实例化IntentFilter
        intentFilter = new IntentFilter();
        //为广播接收器添加系统发出的广播
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        //实例化networkChangeReceiver
        networkChangeReceiver = new NetworkChangeReceiver();
        //注册，实现监听网络变化的功能
        registerReceiver(networkChangeReceiver,intentFilter);
    }
    //动态注册的广播接收器取消注册
    @Override
    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(networkChangeReceiver);
    }

    class NetworkChangeReceiver extends BroadcastReceiver{
        //每当网络状态变化时，onReceive方法执行
        @Override
        public void onReceive(Context context, Intent intent) {
            //Toast提示一段文字信息
            Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show();
        }
    }
}
